/**
 * 
 */
package org.istt.web;

import java.util.List;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.istt.domain.AttachFile;
import org.istt.domain.Category;
import org.istt.domain.Field;
import org.istt.domain.File;
import org.istt.domain.Report;
import org.istt.domain.Workflow;
import org.istt.service.AttachFileManager;
import org.istt.service.CategoryManager;
import org.istt.service.FieldManager;
import org.istt.service.ReportManager;
import org.istt.service.WorkflowManager;
import org.springframework.beans.factory.annotation.Autowired;

import com.opensymphony.xwork2.ActionContext;

/**
 * @author Huy
 *
 */
public class CategoryAction extends BaseAction<CategoryManager, Category, Long> {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 9012754123343759656L;
	private String cateId;
	private String categoryName;
	private String shortName;
	private String description;
	private String workflowId;
	private String fieldId;
	private String reportId;
	private String voucherId;
	private WorkflowManager workflowManager;
	private FieldManager fieldManager;
	private AttachFileManager attachFileManager;
	private CategoryManager categoryManager;
	private List<Field> fields;
	private List<Category> categories;
	@Autowired
	private ReportManager reportManager;
	
	private List<Report> lstReport;
	
	public AttachFileManager getAttachFileManager() {
		return attachFileManager;
	}

	//NDTHO
	private String processTime;
	private String feeNew;
	private String feeChange;
	private String workflowName;
	private String fieldName;
	private Set<AttachFile> files;
	//NDTHO.2011.11.01
	private Boolean isViewOnnet;
	private Boolean isRegisterOnnet;
	
	private String cancel;
	private String delete;
	private String search;
	
	/**
	 * @return the search
	 */
	public String getSearch() {
		return search;
	}

	/**
	 * @param search the search to set
	 */
	public void setSearch(String search) {
		this.search = search;
	}
	
	public String getCancel() {
       return this.cancel;
    }
	
	public void setCancel(String cancel) {
        this.cancel = cancel;
    }

    public void setDelete(String delete) {
        this.delete = delete;
    }
    
    public String getDelete() {
		return delete;
	}
	
	@Override
	public String execute() {
        if (cancel != null) {
        	if(this.fieldId!=null) log.debug("----- FieldId = "+fieldId);
            return "cancel";
        }
        
        if (delete != null) {
            return delete();
        }
        
        if (search != null) {
            return "search";
        }
        
        return SUCCESS;
    }
	
	@Override
	public String delete() {
		if (log.isDebugEnabled()) {
            log.debug("entering 'delete' method");
        }
		if (getId() != null) {
			Category categoryObj = mgr.get(getId()) ;
			Set<File> files = categoryObj.getFiles();
			Set<AttachFile> attFiles = categoryObj.getAttachFiles();
			if((files!=null && files.size()!=0) || (attFiles!=null && attFiles.size()!=0)){
				if(files!=null && files.size()!=0)
					ActionContext.getContext().getSession().put("message", getText("category.delete.error.containFile"));
				if(attFiles!=null && attFiles.size()!=0)
					ActionContext.getContext().getSession().put("message", getText("category.delete.error.containAttachFile"));
				log.debug("entering 'delete error'");			
			}else{
				log.debug("entering 'delete successful'");			
				mgr.remove(getId());
			}
		}else{
			log.debug("entity is null");
		}
        return "delete";
    }
	
	public Set<AttachFile> getFiles() {
		if (entity != null) {
			files = entity.getAttachFiles();
		}
		return files;
	}
	
	public void setFiles(Set<AttachFile> files) {
		this.files = files;
	}

	public String getWorkflowName() {
		return workflowName;
	}

	public void setWorkflowName(String workflowName) {
		this.workflowName = workflowName;
	}
	
    public String getFieldName() {
		return fieldName;
	}

	public void setFieldName(String fieldName) {
		this.fieldName = fieldName;
	}
	
	@Override
	public String edit() throws Exception {
		String forward = super.edit();

		//forward the request to add new process
		if (entity.getId() == null) return forward;
		
		
		return SUCCESS;
	}
	
	/*
	 * Created by NDTHO.2012.02.21
	 */
	public boolean isWorkflowInUsed(){
		log.debug("Enter method isWorkflowInUsed...");
		Category cate = null;
		try {

			entity = getEntity();
			if(getId()!=null) cate = this.categoryManager.get(getId());
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		
		//Checking workflow in used before save
		if(cate!=null){
			
			log.debug("Cate not null..."+cate.getId());
			
			if(cate.getFiles().size()!=0 && (cate.getWorkflow().getId() != entity.getWorkflow().getId())){
				return false;
			}
		}
		
		return true;
	}

	public String getProcessTime() {
		if (entity != null) {
			if(entity.getProcessTime()!=null && !"".equals(entity.getProcessTime()))
				processTime = entity.getProcessTime().toString();
		}
		return processTime;
	}

	public void setProcessTime(String processTime) {
		this.processTime = processTime;
	}

	public String getFeeNew() {
		if (entity != null) {
			if(entity.getFeeNew()!=null && !"".equals(entity.getFeeNew()))
				feeNew = entity.getFeeNew().toString();
		}
		return feeNew;
	}

	public void setFeeNew(String feeNew) {
		this.feeNew = feeNew;
	}

	public String getFeeChange() {
		if (entity != null) {
			if(entity.getFeeChange()!=null && !"".equals(entity.getFeeChange()))
				feeChange = entity.getFeeChange().toString();
		}
		return feeChange;
	}

	public void setFeeChange(String feeChange) {
		this.feeChange = feeChange;
	}

	public String getCode() {
		if (entity != null) {
			code = entity.getCode();
		}
		return code;
	}

	public void setCode(String code) {
		this.code = code;
	}

	private String code;
	
	/**
	 * @return the fieldId
	 */
	public String getFieldId() {
		if (entity != null) {
			if(this.fieldId==null) fieldId = entity.getField() == null ? selDefKey : entity.getField().getId() + "";
		}
		return fieldId;
	}

	/**
	 * @param fieldId the fieldId to set
	 */
	public void setFieldId(String fieldId) {
		this.fieldId = fieldId;
	}

	/**
	 * @return the workflow
	 */
	public String getWorkflowId() {
		if (entity != null) {
			workflowId = entity.getWorkflow() == null ? selDefKey : entity.getWorkflow().getId() + "";
		}
		return workflowId;
	}

	/**
	 * @param workflow the workflow to set
	 */
	public void setWorkflowId(String workflowId) {
		this.workflowId = workflowId;
	}

	/**
	 * @return the workflows
	 */
	public List<Workflow> getWorkflows() {
		return workflowManager.getList();
	}
	
	/**
	 * @return the workflows
	 */
	public List<Field> getFields() {
		return fieldManager.getList();
	}

	/**
	 * @param workflowManager the workflowManager to set
	 */
	public void setWorkflowManager(WorkflowManager workflowManager) {
		this.workflowManager = workflowManager;
	}
	
	/**
	 * @param fieldManager the fieldManager to set
	 */
	public void setFieldManager(FieldManager fieldManager) {
		this.fieldManager = fieldManager;
	}

	/**
	 * @return the categoryName
	 */
	public String getCategoryName() {
		if (entity != null) {
			categoryName = entity.getCategoryName();
		}
		return categoryName;
	}

	/**
	 * @return the description
	 */
	public String getDescription() {
		if (entity != null) {
			description = entity.getDescription();
		}
		return description;
	}

	/**
	 * @param categoryName the categoryName to set
	 */
	public void setCategoryName(String categoryName) {
		this.categoryName = categoryName;
	}
	
	/**
	 * @param description the description to set
	 */
	public void setDescription(String description) {
		this.description = description;
	}

	@Override
	public Category getEntity() {
		Category c = new Category();
		c.setId(getId());
		c.setCategoryName(categoryName);
		c.setShortName(shortName);
		c.setDescription(description);
		c.setFeeChange(NumberUtils.toInt(feeChange));
		c.setFeeNew(NumberUtils.toInt(feeNew));
		c.setCode(code);
		c.setIsRegisterOnnet(isRegisterOnnet);
		c.setIsViewOnnet(isViewOnnet);
		c.setProcessTime(processTime);
		
		//Update reference to REPORT
		if (!StringUtils.isEmpty(reportId) 
				&& !selDefKey.equals(reportId)) {
			Report report = new Report();
			report.setId(NumberUtils.toLong(reportId));
			c.setReport(report);
		}
		
		//Update reference to VOUCHER
		if (!StringUtils.isEmpty(voucherId) 
				&& !selDefKey.equals(voucherId)) {
			Report report = new Report();
			report.setId(NumberUtils.toLong(voucherId));
			c.setVoucher(report);
		}
		
		//Update reference to WORKFLOW
		if (!StringUtils.isEmpty(workflowId) 
				&& !selDefKey.equals(workflowId)) {
			Workflow workflow = new Workflow();
			workflow.setId(NumberUtils.toLong(workflowId));
			c.setWorkflow(workflow);
		}
		
		//Update reference to FIELD
		if (!StringUtils.isEmpty(fieldId) 
				&& !selDefKey.equals(fieldId)) {
			Field field = new Field();
			field.setId(NumberUtils.toLong(fieldId));
			c.setField(field);
		}
		return c;
	}
	
	/**
	 * @return the cateId
	 */
	public String getCateId() {
		return cateId;
	}

	/**
	 * @param cateId the cateId to set
	 */
	public void setCateId(String cateId) {
		this.cateId = cateId;
	}

	@Override
	protected void setSaveMessage() {
        ActionContext.getContext().getSession().put("message", 
                getText("category.saved"));
	}

	@Override
	protected void setDeleteMessage() {
        ActionContext.getContext().getSession().put("message", 
                getText("category.deleted"));
	}

	@Override
	public Long getId() {
		Long id = NumberUtils.toLong(cateId);
		if (id == 0) return null;
		return id;
	}
	
	//NDTHO.2011.11.02
	/***
	 * Purpose: get categories by field 
	 */
	public String listCategoryByField(){
		if(this.fieldId!=null && !"".equals(this.fieldId)){
			categories = categoryManager.getByFieldId(Long.parseLong(this.fieldId));
		}else{
			this.fieldId = fieldManager.getList().get(0).getId().toString();
			categories = categoryManager.getByFieldId(Long.parseLong(this.fieldId));
		}
		return SUCCESS;
	}
	
	public String search() {
    	if (log.isDebugEnabled()) {
            log.debug("entering 'search' method");
        }
    	entities = mgr.search(getEntity());
		return SUCCESS;
	}

	public void setIsRegisterOnnet(Boolean isRegisterOnnet) {
		this.isRegisterOnnet = isRegisterOnnet;
	}

	public Boolean getIsRegisterOnnet() {
		return entity.getIsRegisterOnnet();
	}

	public void setIsViewOnnet(Boolean isViewOnnet) {
		this.isViewOnnet = isViewOnnet;
	}

	public Boolean getIsViewOnnet() {
		return entity.getIsViewOnnet();
	}

	public void setFields(List<Field> fields) {
		this.fields = fields;
	}

	public void setCategories(List<Category> categories) {
		this.categories = categories;
	}

	public List<Category> getCategories() {
		return categories;
	}
	@Autowired
	public void setCategoryManager(CategoryManager categoryManager) {
		this.categoryManager = categoryManager;
	}

	public CategoryManager getCategoryManager() {
		return categoryManager;
	}

	public void setShortName(String shortName) {
		this.shortName = shortName;
	}

	public String getShortName() {
		if (entity != null) {
			shortName = entity.getShortName();
		}
		return shortName;
	}

	public void setReportManager(ReportManager reportManager) {
		this.reportManager = reportManager;
	}

	public ReportManager getReportManager() {
		return reportManager;
	}

	public void setLstReport(List<Report> lstReport) {
		this.lstReport = lstReport;
	}

	public List<Report> getLstReport() {
		return this.reportManager.getList();
	}

	public void setReportId(String reportId) {
		this.reportId = reportId;
	}

	public String getReportId() {
		if (entity != null) {
			reportId = entity.getReport().getId()+"";
		}
		return reportId;
	}

	public void setVoucherId(String voucherId) {
		this.voucherId = voucherId;
	}

	public String getVoucherId() {
		if (entity != null) {
			voucherId = entity.getVoucher().getId() + "";
		}
		return voucherId;
	}
}
